package com.shenzhenai.composesideeffects.samples

import android.util.Log
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.BottomSheetScaffoldState
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier

/**
 * @author huangzehui
 * @date 18/9/2025 下午11:54 周四
 * @description
 *
 * 79-LaunchedEffect
 * https://www.bilibili.com/video/BV1ob4y1a7ad?spm_id_from=333.788.player.switch&vd_source=e07cc8cc94eb22bd76722071b03cd199&p=79
 */


/**
 * @param scaffoldState 脚手架底部状态（可以操作snackbar）
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LaunchEffectSample(
    state: MutableState<Boolean>,
    scaffoldState: BottomSheetScaffoldState = rememberBottomSheetScaffoldState()
) {

    if (state.value) {
        LaunchedEffect(scaffoldState.snackbarHostState) {
            // 这里的使用，必须有设置 Scaffold#snackbarHost 的属性
            scaffoldState.snackbarHostState.showSnackbar(
                message = "Error message",
                actionLabel = "Retry message"
            )
        }
    }


    Scaffold(
        // 标题区域
        topBar = {
            TopAppBar(
                title = {
                    Text(text = "脚手架示例")
                },
            )
        },
        // 屏幕内容区域
        content = { paddingValues ->
            Box(
                modifier = Modifier.padding(paddingValues),
                contentAlignment = Alignment.Center,
            ) {
                Button(onClick = {
//                    state.value = !state.value
                    state.value = true
                }) {
                    Text(text = "Error occurs")
                }
            }
        },
        snackbarHost = {
            // Snackbar 展示
            SnackbarHost(scaffoldState.snackbarHostState)
        }
    )
}

@OptIn(ExperimentalMaterial3Api::class)
//@Preview
@Composable
fun LaunchEffectSamplePreview() {
    val state = remember {
        mutableStateOf(false)
    }
    LaunchEffectSample(state = state)
}